package com.imut.oa.exception;

import com.imut.oa.common.BaseResponse;
import com.imut.oa.common.ErrorCode;
import com.imut.oa.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLException;

@RestControllerAdvice(basePackages = "com.imut.oa.controller")
@Slf4j
public class GlobalExceptionHandler {

    /**
            * 处理业务自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public BaseResponse businessExceptionHandler(BusinessException e) {
        log.error("业务异常 [code:{}] => {}", e.getCode(), e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }

    /**
            * 处理 MyBatis 系统异常
     */
    @ExceptionHandler(MyBatisSystemException.class)
    public BaseResponse myBatisExceptionHandler(MyBatisSystemException e) {
        Throwable rootCause = getRootCause(e);
        log.error("MyBatis 系统异常 => {}", rootCause.getMessage(), e);

        // 根据具体异常类型细化处理
        if (rootCause instanceof SQLException) {
            SQLException sqlEx = (SQLException) rootCause;
            return ResultUtils.error(ErrorCode.DATABASE_ERROR.getCode(),
                    "数据库操作失败",
                    String.format("SQLState: %s | ErrorCode: %d",
                            sqlEx.getSQLState(),
                            sqlEx.getErrorCode()
                    )
            );
        }
        return ResultUtils.error(ErrorCode.DATABASE_ERROR.getCode(), "数据持久化失败", rootCause.getMessage());
    }

    /**
            * 处理通用运行时异常（兜底处理）
            */
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse runtimeExceptionHandler(RuntimeException e) {
        log.error("系统运行时异常 => {}", e.getMessage(), e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR.getCode(),
                "系统繁忙，请稍后再试",
                filterSensitiveInfo(e.getMessage())
        );
    }

    /**
            * 递归获取根本原因
     */
    private Throwable getRootCause(Throwable e) {
        Throwable cause = e.getCause();
        return (cause == null || cause == e) ? e : getRootCause(cause);
    }

    /**
            * 过滤敏感信息（示例）
            */
    private String filterSensitiveInfo(String message) {
        if (message == null) return null;
        // 示例：隐藏密码信息
        return message.replaceAll("(?i)password=.*?(?=[&\\s])", "password=​**​*");
    }
}